<?php

declare (strict_types=1);
namespace App\Service\Store;

use App\Dao\AdvertisingDao;
use App\Dao\BusinessIndustryDao;
use App\Dao\LocationDao;
use App\Service\Service;
use Hyperf\Di\Annotation\Inject;

/**
 * 广告服务
 * Class AdvertisingService
 * @package App\Service\Store
 */
class AdvertisingService extends Service
{
    /**
     * @Inject()
     * @var AdvertisingDao
     */
    public $dao;

    /**
     * @Inject()
     * @var LocationDao
     */
    public $location_dao;

    /**
     * @Inject()
     * @var BusinessIndustryDao
     */
    public $industry_dao;

    /**
     * 根据查询条件获取App首页所有的广告信息
     * @param int $type 广告类型
     * @param int $location_id 投放地区
     * @param array $params 参数
     * @param string $sort 排序
     * @param array $hidden 隐藏字段
     * @return mixed
     */
    public function getIndexAdsList(int $type,int $location_id = 0,array $params = [], string $sort = 'created_at desc', array $hidden = [])
    {
        $map = [];

        isset($params['create_start_time']) &&  !isset($params['create_end_time'])  && !empty($params['create_start_time']) && $map['created_at'] = ['>=', strtotime($params['create_start_time'])]; // 创建开始时间

        isset($params['create_end_time']) &&  !isset($params['create_start_time']) && !empty($params['create_end_time']) && $map['created_at'] = ['<=', strtotime($params['create_end_time'])]; // 创建结束时间

        isset($params['create_end_time']) &&  isset($params['create_start_time'])
        && !empty($params['create_end_time']) && !empty($params['create_start_time'])
        && $map['between_field'] = ['created_at' =>[strtotime($params['create_start_time']), strtotime($params['create_end_time'])]]; // 有创建开始和结束时间

        isset($params['status'])  && $map['status'] = (int)$params['status']; // 广告状态
        isset($params['search']) && !empty($params['search']) && $map['title'] = ['like', "%{$params['search']}%"]; // 搜索关键词

        isset($params['business_name']) && !empty($params['business_name']) && $map['business_name'] = ['like', "%{$params['business_name']}%"]; // 店铺名称
        isset($params['contacts']) && !empty($params['contacts'])  && $map['contacts'] = ['like', "%{$params['contacts']}%"];// 联系人
        isset($params['phone']) && !empty($params['phone']) && $map['phone'] = ['like', "%{$params['phone']}%"]; // 联系方式
        isset($params['industry_id']) && !empty($params['industry_id']) && $map['industry_id'] = (int)$params['industry_id']; // 行业类别ID
        // (修改版)
        if ($location_id > 0) {

            if (isset($params['district_id']) && !empty($params['district_id']) )  { // 区存在时
                $location_id = (int)$params['district_id'];
            } else {
                if ( isset($params['city_id']) && !empty($params['city_id']) ) { // 市存在时
                    $districts = $this->location_dao->getLocationsByMap([
                        'level' => $params['city_id'],
                    ]);
                    $districts = $districts->toArray();
                    $district_ids = array_column($districts, 'pid');
                    $district_ids[] = $params['city_id']; // 城市ID
                    $map['location_id'] = ['in', $district_ids]; // 该城市和旗下所有区
                    $location_id = 0; // 查询时不需要

                } else { // 省ID
                    $cities = $this->location_dao->getLocationsByMap([
                        'level' => $location_id,
                    ]);
                    $cities = $cities->toArray();
                    $city_ids = array_column($cities, 'pid'); // 该省旗下所有市ID
                    $districts = $this->location_dao->getLocationsByMap([
                        'level' => ['in', $city_ids],
                    ]);
                    $districts = $districts->toArray();
                    $district_ids = array_column($districts, 'pid'); // 该省旗下所有区ID
                    $all_ids = array_merge($city_ids, $district_ids, [$location_id]); // 省市区的ID集合
                    $map['location_id'] = ['in', $all_ids];
                    $location_id = 0; // 查询时不需要
                }

            }

        } else {
            $location_id = null;
        }

        // (修改版)

        // 分页
        $page_size = null;
        if (isset($params['page'])) {
            $page_size = 20;
            isset($params['page_size']) && !empty($page_size) && $page_size = (int)$params['page_size'];
        }


        // 提取选项
        $select = ['id', 'type','location_id', 'created_at', 'image', 'title', 'jump_id', 'jump_type','link', 'start_time', 'end_time', 'status', 'position'];

        $appends = ['business_name', 'contacts', 'phone', 'industry_id'];
        $select = array_merge($select, $appends);

        // 查询
        $ads_list = $this->dao->getAdsList($type, $location_id, $map, $sort, $select, $page_size);
        $ads_list = empty($hidden)?$ads_list->toArray():$ads_list->makeHidden($hidden)->toArray();

        if (isset($ads_list['data'])) {
            $ads_list['data'] = $this->joinData($ads_list['data'], $select);
        } else {
            $ads_list = $this->joinData($ads_list, $select);
        }

        return $ads_list;
    }

    /**
     * 连接其他数据库拼接
     * @param array $data
     * @param array $select
     * @return array
     */
    protected function joinData(array $data,array  $select)
    {
        $location_names = null;
        $industry_names = null;
        // 对应location
        if (in_array('location_id', $select)) {
            $location_ids = array_filter(array_column($data,'location_id'));
            $location_names = $this->location_dao->getNameByIds($location_ids)->toArray();
        }
        // 对应business_industry
        if (in_array('industry_id', $select)) {
            $industry_ids = array_filter(array_column($data,'industry_id'));
            $industry_names = $this->industry_dao->getBusinessNameByIds($industry_ids);
        }

        foreach ($data as $key => $item) {
            // 查看是否返回投放位置
            if (isset($item['location_id']) && isset($location_names[$item['location_id']])) {
                $data[$key]['location_name'] = $location_names[$item['location_id']];
            } elseif (!isset($item['location_id']) && in_array('location_id', $select) ) {
                $data[$key]['location_name'] = '无';
            }
            // 查看是否返回行业类型
            if (isset($item['industry_id']) && isset($industry_names[$item['industry_id']])) {
                $data[$key]['industry_name'] = $industry_names[$item['industry_id']];
            } elseif (!isset($item['industry_id']) && in_array('industry_id', $select) )  {
                $data[$key]['industry_name'] = "无";
            }

        }

        return $data;
    }

    /**
     * 广告状态改变
     * @param int $id
     * @return array
     */
    public function statusChange(int $id)
    {
        $status_select = $this->dao->getStatusById($id);
        // 更新后的状态
        $updateStatus = ((int)$status_select['status']) === 1 ?0:1;
        $is_success = $this->dao->update($id,['status' => $updateStatus]);

        if ($is_success) {
            return [
                'is_success' => true,
                'status' => $updateStatus,
            ];
        } else {
            return [
                'is_success' => false,
                'status' => $status_select['status'],
            ];
        }
    }
    
}